package com.leyou.trade.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.DEAD_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.ExchangeConstants.ORDER_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.QueueConstants.DEAD_ORDER_QUEUE;
import static com.leyou.common.constants.MQConstants.QueueConstants.EVICT_ORDER_QUEUE;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.EVICT_ORDER_KEY;

/**
 * @author 虎哥
 */
@Configuration
public class MqConfig {

    /**
     * 订单超时未支付的时间
     */
    private static final long ORDER_QUEUE_DELAY_TIME = 1800000;

    /**
     * 清理订单的 普通交换机
     */
    @Bean
    public TopicExchange orderExchange() {
        return new TopicExchange(ORDER_EXCHANGE_NAME, true, false);
    }

    /**
     * 清理订单的 死信交换机
     */
    @Bean
    public TopicExchange deadExchange() {
        return new TopicExchange(DEAD_EXCHANGE_NAME, true, false);
    }

    /**
     * 死信队列
     */
    @Bean
    public Queue deadOrderQueue() {
        return QueueBuilder.durable(DEAD_ORDER_QUEUE)
                .withArgument("x-dead-letter-exchange", DEAD_EXCHANGE_NAME)
                .withArgument("x-message-ttl", ORDER_QUEUE_DELAY_TIME)
                .build();
    }
    /**
     * 清理订单的任务队列
     */
    @Bean
    public Queue evictOrderQueue() {
        return QueueBuilder.durable(EVICT_ORDER_QUEUE).build();
    }

    /**
     * 绑定死信队列到普通任务交换机
     */
    @Bean
    public Binding deadOrderQueueBinding(){
        return BindingBuilder.bind(deadOrderQueue()).to(orderExchange()).with(EVICT_ORDER_KEY);
    }

    /**
     * 绑定订单清理队列到死信交换机
     */
    @Bean
    public Binding evictOrderQueueBinding(){
        return BindingBuilder.bind(evictOrderQueue()).to(deadExchange()).with(EVICT_ORDER_KEY);
    }

    /**
     * MQ 的消息转换器，用JSON做序列化和反序列化
     */
    @Bean
    public Jackson2JsonMessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }
}
